﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.ServiceModel.Syndication;
using PBDesk.com.Extension.FeedsAggregator;
using PBDesk.Utilities;
using System.IO;
using PBDesk.com.Extension.FeedsAggregator.Entities;

namespace PBDesk.com.Extension.UmbHelper
{
    public class AdminTasks
    {
        public static void WriteTWC9File()
        {
            MyLog.Write<AdminTasks>("AdminTasks::WriteTWC9File()", "Method Call Start");
            bool success = true;
            try
            {
                string fileName = MyUmb.CacheFilesLoc + "TWC9.xml";                
                XmlTextWriter t = new XmlTextWriter(fileName, Encoding.UTF8);
                t.Namespaces = true;
                XDocument xd = XDocument.Load("http://channel9.msdn.com/Shows/This+Week+On+Channel+9/RSS");
                if (xd != null)
                    xd.WriteTo(t);
                t.Flush();
                t.Close();
            }
            catch (Exception ex)
            {
                MyLog.WriteErr<AdminTasks>("Error in AdminTasks::WriteTWC9File()", ex, true);
                success = false;                            
            }
            if (success)
            {
                EmailHelper.SendAdminTaskNotificationEmail("BatchA TWC9 File - done", "BatchA TWC9 File - done");                
            }
            MyLog.Write<AdminTasks>("AdminTasks::WriteTWC9File()", "Method Call End");
        }

        public static void WritePBDeskRssFile()
        {
            MyLog.Write<AdminTasks>("AdminTasks::WritePBDeskRssFile()", "Method Call Start");
            bool success = true;
            try
            {               
                SyndicationFeed feed = FeedHelper.GetPBDeskComRss(100);
                if (feed != null)
                {
                    FileOpHelper.WriteFeedToFile("PBDeskRss.xml", feed);
                }
            }
            catch (Exception ex)
            {
                MyLog.WriteErr<AdminTasks>("Error in AdminTasks::WritePBDeskRssFile()", ex, true);
                success = false;
            }
            
            if (success)
            {
                EmailHelper.SendAdminTaskNotificationEmail("BatchB PBDeskRss File - done", "BatchB PBDeskRss File - done");
            }
            MyLog.Write<AdminTasks>("AdminTasks::WritePBDeskRssFile()", "Method Call End");
        }

        public static void UpdateFeedFiles(string batchJobId)
        {
            MyLog.Write<AdminTasks>("AdminTasks::UpdateFeedFiles()", "Method Call Start for Batch " + batchJobId);
            List<FeedCategory> feedCategories = FeedHelper.GetFeedCategories().Where(p => p.BatchJob == batchJobId).ToList<FeedCategory>();
            if (feedCategories != null && feedCategories.Count > 0)
            {
                foreach (var s in feedCategories)
                {
                    UpdateNewsFeedCache(s);
                }
            }
            MyLog.Write<AdminTasks>("AdminTasks::UpdateFeedFiles()", "Method Call End for Batch " + batchJobId);            

        }
        public static void GenerateNewsFeedsCache()
        {
            MyLog.Write<AdminTasks>("AdminTasks::GenerateNewsFeedsCache()", "Method Call Start");
            List<FeedCategory> feedCategories = FeedHelper.GetFeedCategories();
            if (feedCategories != null && feedCategories.Count > 0)
            {
                foreach (var s in feedCategories)
                {
                    UpdateNewsFeedCache(s);
                }
            }
            MyLog.Write<AdminTasks>("AdminTasks::GenerateNewsFeedsCache()", "Method Call End");
        }

        private static void UpdateNewsFeedCache(FeedCategory category)
        {
            MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Method Call start.");
            StringBuilder emailMessage = new StringBuilder();
            bool success = true;
            if (category != null)
            {
                MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Method Call for " + category.Name);
                SyndicationFeed feed = null;
                try 
                {
                    var items = from url in category.FeedSourceUrls
                                from xr in CustomXmlReader.Create(url).Kill()
                                let feed1 = SyndicationFeed.Load(xr)
                                from i in feed1.Items.OrderByDescending(dt => dt.PublishDate)
                                select i;

                    feed = new SyndicationFeed(category.Title, category.Desc, new Uri(category.Link), items.Distinct().OrderByDescending(dt => dt.PublishDate));
                    feed.Generator = "PBDesk.com Feed Aggrigator";
                    feed.LastUpdatedTime = new DateTimeOffset(DateTime.Now);

                    emailMessage.AppendFormat("\nNo Of soure Links: {0}", category.FeedSourceUrls.Count);
                    emailMessage.AppendFormat("\nNo Of Feed Items Added: {0}", feed.Items.Count());
                    emailMessage.AppendFormat("\nLast Updated Time Stamp: {0}", feed.LastUpdatedTime);

                }
                catch (Exception ex)
                {
                    MyLog.WriteErr<AdminTasks>(String.Format("Error in AdminTasks::UpdateNewsFeedCache({0}) while generating feed object", category.Name), ex, true);
                    success = false;
                }
                try
                {
                    FileOpHelper.WriteFeedToFile(category.CacheFileName, feed);
                }
                catch(Exception ex1)
                {
                    MyLog.WriteErr<AdminTasks>(String.Format("Error in AdminTasks::UpdateNewsFeedCache({0}) while writing to file.", category.Name), ex1, true);
                    success = false;
                }

                if(success)
                    EmailHelper.SendAdminTaskNotificationEmail(category.Name, emailMessage.ToString());

            }
            MyLog.Write<AdminTasks>("AdminTasks::UpdateNewsFeedCache", "Method Call end.");
        }
       

        
    }
}
